<?php
//get wrp data from database by jobid
function wrp_get_data($jobid){
  global $wpdb;
  $wrp_table = $wpdb->prefix.'wrp';
  $query = "SELECT * FROM $wrp_table WHERE id=".$jobid;
  $data = $wpdb->get_row($query, ARRAY_A);	
  return $data;
}

//DoJob
function wrp_do_job($jobid) {
	global $wrp_dojob_message;
	if (empty($jobid))
		return false;
	require_once(dirname(__FILE__).'/wrp_dojob.php');
	$wrp_dojob= new wrp_dojob($jobid);
	unset($wrp_dojob);
	return $wrp_dojob_message;
}


//file size
function wrp_formatBytes($bytes, $precision = 2) {
	$units = array('B', 'KB', 'MB', 'GB', 'TB');
	$bytes = max($bytes, 0);
	$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
	$pow = min($pow, count($units) - 1);
	$bytes /= pow(1024, $pow);
	return round($bytes, $precision) . ' ' . $units[$pow];
}

function wrp_get_file($url){

	if(ini_get('allow_url_fopen') != 1) {
		@ini_set('allow_url_fopen', '1');
	}

	if(ini_get('allow_url_fopen') != 1) {
		
		$ch = curl_init();
 
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Set curl to return the data instead of printing it to the browser.
		curl_setopt($ch, CURLOPT_URL, $url);
 
		$data = curl_exec($ch);
		curl_close($ch);
 
		return $data;

    
	} else {
		return @file_get_contents($url);
	}
	
	return false;

 
}

//////////////////////////////////////////////
// Convert $html to UTF8
// (uses HTTP headers and HTML to find encoding)
// adapted from http://stackoverflow.com/questions/910793/php-detect-encoding-and-make-everything-utf-8
//////////////////////////////////////////////
function wrp_convert_to_utf8($html, $header=null)
{
   $list_encoding = array("pass", "auto", "wchar", "byte2be", "byte2le", "byte4be", "byte4le", "BASE64", "UUENCODE", "HTML-ENTITIES", "Quoted-Printable", "7bit", "8bit", "UCS-4", "UCS-4BE", "UCS-4LE", "UCS-2", "UCS-2BE", "UCS-2LE", "UTF-32", "UTF-32BE", "UTF-32LE", "UTF-16", "UTF-16BE", "UTF-16LE", "UTF-8", "UTF-7", "UTF7-IMAP", "ASCII", "EUC-JP", "SJIS", "eucJP-win", "SJIS-win", "JIS", "ISO-2022-JP", "Windows-1252", "ISO-8859-1", "ISO-8859-2", "ISO-8859-3", "ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "ISO-8859-10", "ISO-8859-13", "ISO-8859-14", "ISO-8859-15", "EUC-CN", "CP936", "HZ", "EUC-TW", "BIG-5", "EUC-KR", "UHC", "ISO-2022-KR", "Windows-1251", "CP866", "KOI8-R");

	$accept = array(
		'type' => array('application/rss+xml', 'application/xml', 'application/rdf+xml', 'text/xml', 'text/html'),
		'charset' => array_diff($list_encoding, array('pass', 'auto', 'wchar', 'byte2be', 'byte2le', 'byte4be', 'byte4le', 'BASE64', 'UUENCODE', 'HTML-ENTITIES', 'Quoted-Printable', '7bit', '8bit'))
	);
	$encoding = null;
	if ($html || $header) {
		if (is_array($header)) $header = implode("\n", $header);
		if (!$header || !preg_match_all('/^Content-Type:\s+([^;]+)(?:;\s*charset=([^;"\'\n]*))?/im', $header, $match, PREG_SET_ORDER)) {
			// error parsing the response
		} else {
			$match = end($match); // get last matched element (in case of redirects)
			if (!in_array(strtolower($match[1]), $accept['type'])) {
				// type not accepted
				// TODO: avoid conversion
			}
			if (isset($match[2])) $encoding = trim($match[2], '"\'');
		}
		if (!$encoding) {
			if (preg_match('/^<\?xml\s+version=(?:"[^"]*"|\'[^\']*\')\s+encoding=("[^"]*"|\'[^\']*\')/s', $html, $match)) {
				$encoding = trim($match[1], '"\'');
			} elseif(preg_match('/<meta\s+http-equiv=["\']Content-Type["\'] content=["\'][^;]+;\s*charset=([^;"\'>]+)/i', $html, $match)) {
				if (isset($match[1])) $encoding = trim($match[1]);
			}
		}
		if (!$encoding) {
			$encoding = 'utf-8';
		} else {
			if (!in_array($encoding, array_map('strtolower', $accept['charset']))) {
				// encoding not accepted
				// TODO: avoid conversion
			}
			if (strtolower($encoding) != 'utf-8') {
				if (strtolower($encoding) == 'iso-8859-1') {
					// replace MS Word smart qutoes
					$trans = array();
					$trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
					$trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
					$trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
					$trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
					$trans[chr(134)] = '&dagger;';    // Dagger
					$trans[chr(135)] = '&Dagger;';    // Double Dagger
					$trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
					$trans[chr(137)] = '&permil;';    // Per Mille Sign
					$trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
					$trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
					$trans[chr(140)] = '&OElig;';    // Latin Capital Ligature OE
					$trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
					$trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
					$trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
					$trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
					$trans[chr(149)] = '&bull;';    // Bullet
					$trans[chr(150)] = '&ndash;';    // En Dash
					$trans[chr(151)] = '&mdash;';    // Em Dash
					$trans[chr(152)] = '&tilde;';    // Small Tilde
					$trans[chr(153)] = '&trade;';    // Trade Mark Sign
					$trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
					$trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
					$trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
					$trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
					$html = strtr($html, $trans);
				}
				if(!class_exists('SimplePie_Misc'))
					require_once('simplepie.inc');

				$html = SimplePie_Misc::change_encoding($html, $encoding, 'utf-8');

				/*
				if (function_exists('iconv')) {
					// iconv appears to handle certain character encodings better than mb_convert_encoding
					$html = iconv($encoding, 'utf-8', $html);
				} else {
					$html = mb_convert_encoding($html, 'utf-8', $encoding);
				}
				*/
			}
		}
	}
	return $html;
}

function wrp_full_feed($permalink, &$campagin, &$item){

	require_once('readability.php');

	if ($permalink && $html = wrp_get_file($permalink)) {
		
		$html = wrp_convert_to_utf8($html);

		$content = grabArticleHtml($html);

		
	}else
		return false;

	if( false !== stripos($content,'readability was unable to parse this page for content') )
		return false;
	if( false !== stripos($content, 'return go_back();') )
		return false;
	
	
	$origin_array = explode(",", $$campagin['origin']);
	$rewrite_array = explode(",", $$campagin['rewrite']);
	
	foreach($origin_array as $key => $value){
	  	$content = str_ireplace(trim($value), stripslashes(trim($rewrite_array[$key])), $content);
	  	
	}	
	if($campagin['source_link'] == 'true'){
		$content .= '<br />Source Article from <a href="'.$permalink.'">'.$permalink.'</a>';
	}	
	
	/*
	if($campaign['cache_image'] == 'true') {
		$content=wrp_content_fix($content);
	    $content=wrp_parse_images($content,$item->get_base());	
	 }
	*/
	
	return $content;

}

function wrp_content_fix($text){
	preg_match_all('@(<a.+?href=\".+?\">)(.*?</a>)@',$text,$m);
	$urls = $m[1];
	if(count($urls)){
		foreach($urls as $pos => $link){
			if(false === stripos($link,'http://') && false === stripos($link,'https://')){
		
				$text=str_replace($link,'',$text);
		
				$text=str_replace($m[2][$pos],str_replace('</a>','',$m[2][$pos]),$text);
			}
		}
	}
	$text=preg_replace("/[&|#|&#]+[a-z0-9]+;/i","",$text);
	$text=preg_replace('@<[dtrx][^>]*>@','',$text);
	$text=preg_replace('@</[dtrx][^>]*>@','',$text);
	return $text;

}

function wrp_parse_images($content,$link){
	
	preg_match_all('/<img(.+?)src=\"(.+?)\"(.*?)>/', $content, $images);
	$urls = $images[2];
       
      	if(count($urls)){

		foreach($urls as $pos => $url){
			$oldurl=$url;
			$meta=parse_url($url);
			
			if(!isset($meta['host'])){

				$meta=parse_url($link);
				$url=$meta['scheme'].'://'.$meta['host'].'/'.$url;
				
   			}
			
          		$newurl = wrp_cache_image($url);
          		if($newurl)
            			$content = str_replace($oldurl, $newurl, $content);
			else
				$content = str_replace($images[0][$pos],'',$content);
        	} 
        }
	return $content;
   	


} 	

function wrp_cache_image($url){
	if( strpos($url, "icon_") !== FALSE)
	      return false;
	global $rpf_options;
	$contents = wrp_get_file($url);
	
	if( !$contents )
		return false;
	$basename = basename($url);
	$paresed_url = parse_url($basename);
	
	$filename = substr(md5(time()), 0, 5) . '_' . $paresed_url['path'];
    	
	
	$pluginpath = WRP_URL;
    	$real_cachepath=dirname(dirname(__FILE__)).'/cache';
	if(is_writable(	$real_cachepath ) ){
		
		if($contents){

			file_put_contents($real_cachepath . $filename, $contents);
			$i=@exif_imagetype($real_cachepath . $filename);
			if($i)
				return $pluginpath . $cachepath . rawurlencode($filename);
		}
	}else{
		
		echo " directory is not writable";
		
	}
    
	return false;

}

function wrp_log($message){
   
}

//*********************************************************************************************************
  /**
   * Parses a feed with SimplePie
   *
   * @param   boolean     $stupidly_fast    Set fast mode. Best for checks
   * @param   integer     $max              Limit of items to fetch
   * @return  SimplePie_Item    Feed object
   **/
  function fetchFeed($url, $stupidly_fast = false, $max = 0) {
    # SimplePie

	if (!class_exists('SimplePie')) {
		if (is_file(trailingslashit(ABSPATH).'wp-admin/includes/class-simplepie.php'))
			include_once( trailingslashit(ABSPATH).'wp-admin/includes/class-simplepie.php' );
		else
			//include_once('class-simplepie.php');
			include_once('simplepie.inc');
	}		
    $feed = new SimplePie();
    $feed->enable_order_by_date(false);
    $feed->set_feed_url($url);
    $feed->set_item_limit($max);
    $feed->set_stupidly_fast(true);
    $feed->enable_cache(false);    
    $feed->init();
    $feed->handle_content_type(); 
    
    return $feed;
  }
?>
